package com.kuangstudy.entity;

import com.alibaba.fastjson.annotation.JSONField;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Description: UserDetails的实现类
 * ===说明：这里遇到一个坑，redis的key和value在序列化的时候是调用get/set方法，不写的话redis中是存不进去的！===
 * Author: ryt
 * Version: 1.0
 * Create Date Time: 2021/12/21 16:06.
 */
public class LoginUser implements UserDetails {

    private User user;

    public List<String> getPremissions() {
        return premissions;
    }

    public void setPremissions(List<String> premissions) {
        this.premissions = premissions;
    }

    // 用户权限信息
    private List<String> premissions;

    // 不让redis进行序列化的存储,排除redis对它的序列化
    @JSONField(serialize = false)
    private List<SimpleGrantedAuthority> authorities;


    public LoginUser() {
    }

    public LoginUser(User user, List<String> premissions) {
        this.user = user;
        this.premissions = premissions;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    // 返回用户的权限信息
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 1、判断用户当前的权限信息的集合是否为空，不为空直接返回（就不用重复的进行赋值了）
        if (!CollectionUtils.isEmpty(authorities)) {
            return authorities;
        }

        // 转换集合
        // 2、把premissions中的权限信息封装成 SimpleGrantedAuthority对象，
        // 再将SimpleGrantedAuthority对象 存入到Authentication中
        authorities = premissions.stream().
                map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        return authorities;
    }

    // 返回用户的密码
    @Override
    public String getPassword() {
        return user.getPassword();
    }

    // 返回用户的用户名
    @Override
    public String getUsername() {
        return user.getUserName();
    }

    // 判断用户是否没有过期
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    // 判断用户是否没有被锁定
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    // 判断是否用户凭证没有过期
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    // 判断用户状态是否可用
    @Override
    public boolean isEnabled() {
        return true;
    }
}
